package com.yanfan.ibms.common.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

import java.io.*;
import java.net.Socket;

/**
 * tcp工具类
 */
public class TcpUtil {

    /**
     * // 连接到服务器并发送命令
     * @param serverAddress 报警主机ip
     * @param serverPort 端口号
     * @param command  json格式命令
     * @return  返回json数据
     */
    public static JSONObject sendCommand(String serverAddress,int serverPort,JSONObject command) {
        try (Socket socket = new Socket(serverAddress, serverPort)) {
            // 获取输出流
            OutputStream output = socket.getOutputStream();
            PrintWriter writer = new PrintWriter(output, true);

            // 发送JSON命令
            writer.println(command.toJSONString());

            // 获取输入流
            InputStream input = socket.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(input));

            // 读取服务器响应
            String response = reader.readLine();

            // 解析JSON响应
            return JSON.parseObject(response);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

}
